/* =========================================
 *      消息存储子服务的客户端测试搭建 
 * =========================================*/

#include "etcd.hpp"
#include "channel.hpp"
#include "base.pb.h"
#include "message_storage.pb.h"
#include "utils.hpp"
#include <boost/date_time/posix_time/conversion.hpp>
#include <boost/date_time/posix_time/time_formatters.hpp>
#include <boost/date_time/posix_time/time_parsers.hpp>
#include <brpc/controller.h>
#include <cstdint>
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include <iostream>
#include <string>

DEFINE_bool(run_mode, false, "程序的运行模式: false-调试 true-发布");
DEFINE_string(log_file, "", "指定日志的输出文件");
DEFINE_int32(log_level, 0, "指定日志输出等级");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(message_service, "/service/message_service", "当前监控的服务");

shared::infra::RpcServiceManagerPtr rpcServiceMgr;

void print(const im_proto::MessageInfo& msg)
{
    std::cout << msg.message_id() << '\n';
    std::cout << msg.chat_session_id() << '\n';
    std::cout << boost::posix_time::to_simple_string(boost::posix_time::from_time_t(msg.timestamp())) << '\n';
    std::cout << msg.sender().user_id() << '\n';
    std::cout << msg.sender().nickname() << '\n';
    std::cout << msg.sender().avatar() << '\n';

    switch ((int)msg.message().message_type()) {
        case im_proto::MessageType::STRING:
            std::cout << "文本消息：" << msg.message().string_message().content() << '\n';
            break;
        case im_proto::MessageType::IMAGE:
            std::cout << "图片消息：" << msg.message().image_message().image_content() << '\n';
            break;
        case im_proto::MessageType::FILE:
            std::cout << "文件消息：" << msg.message().file_message().file_contents() << '\n';
            std::cout << "文件名称：" << msg.message().file_message().file_name() << '\n';
            std::cout << "文件大小：" << msg.message().file_message().file_size() << '\n';
            break;
        case im_proto::MessageType::SPEECH:
            std::cout << "语音消息：" << msg.message().speech_message().file_contents() << '\n';
            break;
        default:
            std::cout << "类型错误！！\n";
    }
}

TEST(GetHisMessageTest, Recent)
{
    auto channel = rpcServiceMgr->choose(FLAGS_message_service); 
    ASSERT_TRUE(channel);

    std::string chatSessionId = "session-1";
    uint32_t msgCount = 3;
    im_proto::GetRecentHisMsgReq req;
    req.set_request_id(shared::Uuid::createUuid());
    req.set_chat_session_id(chatSessionId);
    req.set_msg_count(msgCount);

    brpc::Controller controller;
    im_proto::GetRecentHisMsgRsp resp;
    im_proto::MsgStorageService_Stub stub(channel.get());
    stub.GetRecentHisMsg(&controller, &req, &resp, nullptr);
    ASSERT_FALSE(controller.Failed());
    ASSERT_TRUE(resp.success());

    auto msgList = resp.msg_list();
    ASSERT_EQ(msgList.size(), msgCount);

    for (auto& msg : msgList) {
        std::cout << "---------------------- 获取最近消息 ---------------------------\n";
        print(msg);
    }
}

TEST(GetHisMessageTest, Range)
{
    auto channel = rpcServiceMgr->choose(FLAGS_message_service); 
    ASSERT_TRUE(channel);

    std::string chatSessionId = "session-1";
    boost::posix_time::ptime sp = boost::posix_time::time_from_string("2025-09-26 13:25:00");
    boost::posix_time::ptime ep = boost::posix_time::time_from_string("2025-09-26 13:29:59");
    im_proto::GetRangeHisMsgReq req;
    req.set_request_id(shared::Uuid::createUuid());
    req.set_chat_session_id(chatSessionId);
    req.set_start_time(boost::posix_time::to_time_t(sp));
    req.set_over_time(boost::posix_time::to_time_t(ep));

    brpc::Controller controller;
    im_proto::GetRangeHisMsgRsp resp;
    im_proto::MsgStorageService_Stub stub(channel.get());
    stub.GetRangeHisMsg(&controller, &req, &resp, nullptr);
    ASSERT_FALSE(controller.Failed());
    ASSERT_TRUE(resp.success());

    auto msgList = resp.msg_list();
    ASSERT_EQ(msgList.size(), 2);

    for (auto& msg : msgList) {
        std::cout << "---------------------- 获取范围消息 ---------------------------\n";
        print(msg);
    }
}

TEST(GetHisMessageTest, QuerySearch)
{
    auto channel = rpcServiceMgr->choose(FLAGS_message_service); 
    ASSERT_TRUE(channel);

    std::string chatSessionId = "session-1";
    im_proto::HisMsgSearchReq req;
    req.set_request_id(shared::Uuid::createUuid());
    req.set_chat_session_id(chatSessionId);
    req.set_search_key("uid1");

    brpc::Controller controller;
    im_proto::HisMsgSearchRsp resp;
    im_proto::MsgStorageService_Stub stub(channel.get());
    stub.HisMsgSearch(&controller, &req, &resp, nullptr);
    ASSERT_FALSE(controller.Failed());
    ASSERT_TRUE(resp.success());

    auto msgList = resp.msg_list();
    ASSERT_EQ(msgList.size(), 1);

    for (auto& msg : msgList) {
        std::cout << "---------------------- 搜索结果 ---------------------------\n";
        print(msg);
    }
}

int main(int argc, char* argv[])
{
    testing::InitGoogleTest(&argc, argv);
    google::ParseCommandLineFlags(&argc, &argv, true);
    shared::init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    // 1.构造rpc服务管理对象
    rpcServiceMgr = std::make_shared<shared::infra::RpcServiceManager>();
    rpcServiceMgr->declared(FLAGS_message_service);   
    auto putCb = std::bind(
        &shared::infra::RpcServiceManager::onServiceOnline, rpcServiceMgr.get(), std::placeholders::_1, std::placeholders::_2
    );
    auto delCb = std::bind(
        &shared::infra::RpcServiceManager::onServiceOffline, rpcServiceMgr.get(), std::placeholders::_1, std::placeholders::_2
    );

    // 2.构造服务发现对象
    shared::infra::DiscoveryPtr client = std::make_shared<shared::infra::Discovery>(
        FLAGS_etcd_host, FLAGS_base_service, putCb, delCb
    );

    return RUN_ALL_TESTS();
}